<template>
  <div class="basic-profile-info">
    <el-form ref="ruleFormRef" :model="userInfoForm" :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="民族" prop="ethnicity">
        <el-select v-model="userInfoForm.ethnicity" filterable>
          <el-option v-for="item in ETHNICITY_LIST" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveUserInfoHandler(ruleFormRef)">保存</el-button>
        <el-button @click="closeHandler">关闭</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from "element-plus";
import type { User } from "@/typings";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import { reactive, ref, onMounted } from "vue";
import { useKeepAliveStore, useTabsStore, useUserStore } from "@/stores";
import { ETHNICITY_LIST } from "@/config";
defineOptions({
  name: "BasicProfileInfo"
});
type UserInfoForm = User;
const useUser = useUserStore();
const route = useRoute();
const tabStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const ruleFormRef = ref<FormInstance>();
const userInfoForm: UserInfoForm = reactive({} as UserInfoForm);

/**
 * @description 规则校验
 */
const rules = reactive<FormRules<typeof userInfoForm>>({
  nickName: [{ min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }]
});

onMounted(() => {
  initUserInfo();
});

/**
 * @description 初始化用户信息
 */
const initUserInfo = () => {
  Object.assign(userInfoForm, useUser.userInfo);
};

/**
 * @description 保存用户信息
 */
const saveUserInfoHandler = (ruleForm: FormInstance | undefined) => {
  if (!ruleForm) return false;
  ruleForm.validate((valid: boolean) => {
    if (!valid) {
      ElMessage.error("请填写正确的表单信息进行提交");
      return;
    }
    console.log("保存用户信息", userInfoForm);
  });
};

/**
 * @description 关闭
 */
const closeHandler = () => {
  const fullPath = route.fullPath;
  const name = tabStore.tabsMenuList.filter((item) => item.path == fullPath)[0].name || "";
  keepAliveStore.removeKeepAliveName(name);
  tabStore.closeTab(fullPath as string, true);
};
</script>

<style scoped lang=""></style>
